package cn.springcloud.fix.common.starter.utils.barcode;

import cn.springcloud.fix.common.starter.utils.barcode.components.MatrixToImageWriterEx;
import cn.springcloud.fix.common.starter.utils.barcode.vo.QrcodeVo;
import com.google.zxing.common.BitMatrix;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URISyntaxException;

public class QrcodeUtil {

    /**
     * 生成二维码
     *
     * @param qrcodeVo 输入参数，必填
     * @return BufferedImage 图片流
     */
    public static BufferedImage createImageStream(QrcodeVo qrcodeVo) throws URISyntaxException, IOException {
        if (qrcodeVo.getWidth() == null) {
            qrcodeVo.setWidth(300);
        }

        if (qrcodeVo.getHeight() == null) {
            qrcodeVo.setHeight(300);
        }

        BitMatrix matrix = MatrixToImageWriterEx.createQRCode(qrcodeVo);
        if (qrcodeVo.getMargin() != null && qrcodeVo.getMargin() == 0) {
            matrix = deleteWhite(matrix);
        }

        return MatrixToImageWriterEx.writeToStream(matrix, qrcodeVo);
    }

    public static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1])) {
                    resMatrix.set(i, j);
                }
            }
        }
        return resMatrix;
    }
}
